<template>
  <breadCrumb ref="breadcrumb" :item='item'></breadCrumb>
	<div class="table-wrapped">
    <!-- 1. 表格部分 -->
    <div class="table-top">
      <!-- 1-1. 上传 -->
      <div class="table-header">
				<div></div>
				<div class="upload-wrapped">
          <!-- action 属性指定了上传文件的接口地址； on-exceed 事件在用户尝试上传超过 limit 设置的文件数量时触发； -->
           <!-- on-success 事件在文件上传成功时触发；show-file-list==false，表示不显示文件列表,UI 会显示一个文件列表，这里将其关闭 -->
					<el-upload v-model:file-list="fileList" class="upload-demo" :action="fileUrl" multiple :limit='3' :on-exceed='handleExceed'
						:on-success="handleSuccess" :show-file-list='false'>
						<el-button type="primary">上传文件</el-button>
					</el-upload>
				</div>
			</div>
      <!-- 1-2. 表格-->
      <div class="table-content">
				<el-table :data='tableData' style="width: 100%;">
					<el-table-column type="index" width="50" :index="indexMethod"></el-table-column>
					<el-table-column prop="file_name" label="文件名" />
					<el-table-column prop="file_size" label="文件大小" >
						<template #default="{row}">
							<div>{{(row.file_size * 1 )?.toFixed(1)}}KB</div>
						</template>
					</el-table-column>
					<el-table-column prop="upload_person" label="上传者" />
					<el-table-column prop="download_number" label="下载次数" />
					<el-table-column prop="upload_time" label="上传时间" width="200">
						<template #default="{row}">
							<div>{{row.upload_time?.slice(0,10)}}</div>
						</template>
					</el-table-column>

					<el-table-column label="操作" width="300" fixed="right">
						<template #default="{row}">
							<div>
								<el-button type="success">
									<template #default>
										<a :href="row.file_url" @click="changeClick(row.download_number,row.id)">下载文件</a>
									</template>
								</el-button>
								<el-button type="danger" @click="deleteFile(row)">删除</el-button>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
    </div>

    <!-- 2. 页脚 -->
    <div class="table-footer">
			<el-pagination :page-size="1" :current-page="paginationData.fileCurrentPage" :pager-count="7" :total="paginationData.fileTotal" 
        :page-count="paginationData.filePageCount" @current-change="fileCurrentChange" layout="prev, pager, next" />
		</div>
  </div>

  <tips ref="tip" @success='getFileFirstPageList'></tips>
</template>
 
<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import breadCrumb from '@/components/bread_crumb.vue';
  import { bindFileAndUser, fileListLength, returnFilesListData, updateDownload } from '@/api/file.js';
  import { bus } from "@/utils/mitt.js";
  import tips from './components/tips.vue';
  import type { UploadProps, UploadUserFile } from 'element-plus'; 

  const breadcrumb = ref() 
	const item = ref({
		first: '合同管理（文件管理）',
	})

	const indexMethod = (index:number) => { // index从0开始 
	if(paginationData.fileCurrentPage===1){
			return index+1
		}else{
			return (paginationData.fileCurrentPage-1) * 10 + (index+1)
		}
	}

  const fileList = ref < UploadUserFile[] > ([])
  const fileUrl = ref(`${import.meta.env.VITE_API_BASEURL}/file/uploadFile`)
  // const fileUrl = ref('http://127.0.0.1:3007/file/uploadFile') // action 属性指定了上传文件的接口地址

  // 文件表格数据
	const tableData = ref([])

  // 文件数量限制回调
	const handleExceed: UploadProps['onExceed'] = () => {
		ElMessage.warning('最多上传三个文件！')
	}

  // 文件上传成功回调  
	const handleSuccess = (response: any) => {
		if (response.status == 0) {
			(async () => {
				await bindFileAndUser(localStorage.getItem('name'), response.url)
			})()
			ElMessage({
				message: '上传文件成功',
				type: 'success',
			})
			getFileFirstPageList()
		} else {
			ElMessage.error('上传文件失败，请检查网络问题！')
		}
	}

  // 分页数据
	const paginationData = reactive({ 
		fileTotal: 1, // 文件总数 
		filePageCount: 1, // 文件列表总页数 
		fileCurrentPage: 1, // 文件列表当前所处页数
	})

  // 获取文件列表的页数
	const getFileListLength = async () => {
		const res = await fileListLength()
		paginationData.fileTotal = res.data.length
		paginationData.filePageCount = Math.ceil(res.data.length / 10)
	}
	getFileListLength()

  // 文件列表监听换页
	const fileCurrentChange = async (value: number) => {
		paginationData.fileCurrentPage = value
		const res = await returnFilesListData(paginationData.fileCurrentPage)
    tableData.value = res.data
	}

  // 默认获取文件列表第一页的数据
	const getFileFirstPageList = async () => {
		const res = await returnFilesListData(1)
    tableData.value = res.data
	}
	getFileFirstPageList()

  // 更新点击率
	const changeClick = async (download_number: number, id: number) => {
		await updateDownload(download_number, id)
	}

  const tip = ref()
	const deleteFile = (row: any) => {
		bus.emit('deleteFile', row)
		tip.value.open()
	}
</script>
 
<style lang="scss" scoped>
	:deep(.el-table .cell) {
		font-weight: 400;
	}
	
	a {
		color:#fff;
		display: block;
		text-decoration: none;
	}
</style>